package io.github.liuqun.sandbox.common;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadLocalRandom;

public class DesensitizationUtils {
    /**
     * 对用户手机号/密码等隐私内容进行脱敏处理
     *
     * @param sensitiveToken 例: 输入 "password"
     * @return 例: 输出 "p*********d"; 备注: 输出*的个数应随机变化, 以避免暴露原文长度
     */
    public static String tokenDesensitize(String sensitiveToken) {
        ThreadLocalRandom current = ThreadLocalRandom.current();
        // 随机生成N个"*"星号
        int rand = current.nextInt(3, 11);

        if (StringUtils.isEmpty(sensitiveToken) || sensitiveToken.length()<=2) {
            // 若输入字符串长度太短则随机生成前后缀ASCII码和N个星号, 不允许暴露密码长度
            int ch = current.nextInt(((int)'A'), ((int)'z' + 1));
            int digit = ((int)'0') + current.nextInt(10);
            return (char)ch + StringUtils.repeat("*", rand) + (char)digit;
        }
        return sensitiveToken.charAt(0) + StringUtils.repeat("*", rand) +
                sensitiveToken.charAt(sensitiveToken.length()-1);
    }
}
